package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException exception) {
        return Result.error(exception.getMessage());
    }

    /**
     * 处理sql异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        String message = exception.getMessage();
        if (message.contains("Duplicate entry")) {
            String errorMessage = message.split(" ")[2];
            return Result.error(errorMessage + "已经存在");
        } else {
            return Result.error("出现了未知的异常");
        }
    }
}
